from web_ import constants
from web_.models import User, News, Category
from web_.utils.response_code import RET
from . import index_blue
from flask import render_template, current_app, session, request, jsonify, g
from web_.utils.common import user_login_data

@index_blue.route('/news_list')
def new_list():
    '''
    新闻展示
    1.接收参数
    2.校验参数
    4.查询数据
    5.返回数据
    :return:
    '''
    # 1.接收参数 【get】请求
    cid = request.args.get('cid', 1)  # 分类id
    page = request.args.get('page', 1)  # 页数
    per_page = request.args.get('per_page', 10)  # 每页展示数据
    # 2.校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 3.查询数据
    filters = [News.status == 0]
    if cid != 1:
        filters.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    cid_list = paginate.items  # 模型对象列表
    # 获取到总页数
    total_page = paginate.pages
    current_page = paginate.page
    news_li = []
    for new in cid_list:
        news_li.append(new.to_basic_dict())

    data = {
        'news_li': news_li,
        'total_page': total_page,
        'current_page': current_page
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@index_blue.route('/')
@user_login_data
def index():
    '''
    1：查看登录状态
    2：右边排行榜的界面
    :return:
    '''
    # 1：查看登录状态
    # 在SESSION中拿到登陆状态
    # user_id = session.get('user_id')
    # # 如果有值显示，没有执行下方
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as f:
    #         current_app.logger.error(f)
    # 以上是登录状态
    # 2：右边排行榜的界面
    # 1.接收参数 # 2.校验参数 # 3.从数据库取值# 4，返回数据

    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    #  分类展示
    #   在分类数据库中查找
    try:
        categorys = Category.query.all()
    except Exception as f:
        current_app.logger.error(f)
    category_dict_list = []
    for category in categorys:
        category_dict_list.append(category.to_dict())
    data = {
        'user':g.user.to_dict() if g.user else None,
        'news_dict_list': news_dict_list,
        'category_dict_list': category_dict_list
    }
    return render_template('news/index.html', data=data)


@index_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
